package org.openqa.selenium.profiler.testserver;

import java.util.concurrent.Future;

import org.openqa.selenium.net.PortProber;
import org.webbitserver.HttpHandler;
import org.webbitserver.WebServer;
import org.webbitserver.WebServers;
import org.webbitserver.handler.StringHttpHandler;

public class AppServer {
  public static String serveHandlerOnce(HttpHandler delegateHandler) {
    RunOnceHandler handler = new RunOnceHandler(delegateHandler);
    WebServer server = WebServers
        .createWebServer(PortProber.findFreePort())
        .add(handler);
    handler.setServer(server);

    Future<? extends WebServer> future = server.start();
    while (!future.isDone()) {
      Thread.yield();
    }
    return server.getUri().toString();
  }

  public static String serveHtmlOnce(String html) {
    return serveHandlerOnce(new StringHttpHandler("text/html", html));
  }

  public static String serveBodyOnce(String body) {
    return serveHtmlOnce("<html><body>" + body + "</body></html>");
  }
}
